# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo, donggu

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def gen_var_ticks(quote):
  if 'USDT' == quote:
    price_list = [1e9, 0]
    tick_list = [0.001]
  elif 'BTC' == quote:
    price_list = [1e9, 0]
    tick_list = [0.00000001]
  elif 'KRW' == quote:
    price_list = [1e9, 2000000., 1000000., 500000., 100000., 10000., 1000., 100., 10., 1., 0.1, 0]
    tick_list = [1000., 500., 100., 50., 10., 5., 1., 0.1, 0.01, 0.001, 0.0001]

  range_list = list(zip(price_list[:-1], price_list[1:]))
  result = []
  for r, tick in zip(range_list, tick_list):
    assert r[0] > r[1]
    info = {
        'from': r[1],
        'to': r[0],
        'value': tick,
    }
    result.append([info['from'], info['to'], info['value']])
  return result


def gen_min_amount(quote):
  if 'USDT' == quote:
    return 0.0005
  elif 'BTC' == quote:
    return 0.0005
  elif 'KRW' == quote:
    return 5000


def generate():
  mea = 'Spot.Upbit.v1'
  me = 'Spot.Upbit'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get('https://api.upbit.com/v1/market/all?isDetails=false').json()

  pis = []
  for info in data:
    native_symbol = info['market']
    native_quote, native_base = native_symbol.split('-')
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        is_inverse=False,
        price_ticksize=gen_var_ticks(quote),
        qty_ticksize=0.0001,
        min_amount=gen_min_amount(quote),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  base_currency_list = [info['native_base'] for info in data]
  res = {
      'coin_list': list(set(base_currency_list)),
  }
  return res


if __name__ == '__main__':
  import json
  config = generate()
  print(json.dumps(config, indent=2))
